// HostNameResolver.cs
// 
// Modified slightly for bareFTP by Christian Eide <christian@bareftp.org>
//
// Original copyright notice:
// -------------------
// 
// Copyright (C) 2004 Enterprise Distributed Technologies Ltd
// 
// www.enterprisedt.com
// 
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// 
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

using System;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;

namespace Sarnata.Net.BareFtp.Protocol
{
		
	public class HostNameResolver
    {
        private const string IP_ADDRESS_REGEX = @"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}";

        public static IPAddress GetAddress(string hostName)
        {
            if (hostName == null)
                throw new ArgumentNullException();
            IPAddress address = null;
            if (Regex.IsMatch(hostName, IP_ADDRESS_REGEX))
                address = IPAddress.Parse(hostName);
            else
            {
                IPAddress[] addresses = Dns.GetHostEntry(hostName).AddressList;
                // see if there's an IPv4 address
                foreach (IPAddress a in addresses)
                    if (a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        address = a;
                // otherwise throw an exception coz we don't handle IPv6 yet.
                if (address == null)
                    throw new ArgumentException(hostName + " resolves to an unsupported protocol.");
			}
            return address;
        }
    }
}
